package cn.wawi.controller.business;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import cn.wawi.common.interceptor.SellerTokenInterceptor;
import cn.wawi.controller.BaseController;
import cn.wawi.model.business.Packet;
import cn.wawi.model.business.Packetitem;
import cn.wawi.model.business.Serviceitem;

import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.JsonRender;

@ControllerBind(controllerKey="/packet")
public class PacketController extends BaseController<Packet> {

	
	
    @Before(Tx.class)  
	public void addPacketAndItem(){
	  Packet packet =	getModel(Packet.class);
	  packet.setMoney(new BigDecimal(getRequest().getParameter("money")));
	  packet.save();
	  int fenmu=0;
	  String[] xs = packet.getProportion().split(":");
	  for(String y:xs)
	  {
		  fenmu+=Integer.valueOf(y);
	  }
	  
	  Map<String,String[]> map = getRequest().getParameterMap();
	  int k = (map.size()-4)/4;
	  
	  for(int x=0;x<k;x++)
	  {
		   Packetitem pi = new Packetitem();
		   pi.setId(packet.getId());
		   pi.setMoney(packet.getMoney().multiply(BigDecimal.valueOf(Integer.valueOf(xs[x])/(double)fenmu)));
		   pi.setTime(Integer.valueOf(getRequest().getParameter("time_"+x)));
		   pi.setCount(Integer.valueOf(getRequest().getParameter("count_"+x)));
		   pi.setServiceId(Integer.valueOf(getRequest().getParameter("serviceId_"+x)));
		   Serviceitem si = Serviceitem.dao.findById(pi.getServiceId());
		   pi.setServiceName(si.getName());
		   pi.save();
	  }
	   render(new JsonRender(json).forIE());
		
		
	}
	
	
   
 //  @Before(SellerTokenInterceptor.class)
   public void findAllPacket(){
		Page<Packet> list=getModel(Packet.class).paginateMysql(toPageIndex(), toPageSize(),getSql());

		for(Packet packet :list.getList())
		{
		
			List<Record>  lt = Db.find("select A.*,B.name from  packetitem A inner join serviceitem B on A.serviceid = B.id and A.id =? ",packet.getId());
			List<Packetitem> q = new ArrayList<Packetitem>();
			for(Record rc: lt)
			{
				Packetitem pi = new Packetitem();
				pi.setServiceId(rc.getInt("serviceId"));
				pi.setTime(rc.getInt("time"));
				pi.setCount(rc.getInt("count"));
			    pi.setMoney(rc.getBigDecimal("money"));
			    pi.setServiceName(rc.getStr("name"));
			    q.add(pi);
			}
			packet.setPacketItems(q);
			
		} 
		
	   json.setRows(list.getList());
	   json.setTotal(list.getTotalRow()+0L);
	   json.setPageNumber(list.getPageNumber());
	   json.setPageSize(list.getPageSize());
	   json.setTotalPage(list.getTotalPage());
	   
	   
	   
	   render(new JsonRender(json).forIE());

   }
	
	
}
